<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="160px">

      <el-form-item label="用户昵称或用户名" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入用户昵称或用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item label="排班时间范围" style="width: 408px">
        <el-date-picker
            v-model="daterange1"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="formatDateRange"
        ></el-date-picker>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['attendance:attendance:add']"
        >批量新增默认排班</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--展示表单-->

      <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="用户姓名" align="center" prop="userName" />
        <el-table-column label="职位" align="center" prop="position" />


        <!-- 动态日期列 -->
        <el-table-column
            v-for="date in dateRangeDays"
            :key="date"
            :label="formatDateLabel(date)"
            align="center"
            :prop="`date_${date.replace(/-/g, '_')}`"
        >
          <template #default="scope">
          <span
              class="cell-content"
              @click="handleCellClick(scope.row, date, $event)"
              :style="{ cursor: 'pointer' }"
          >
            {{ getAttendanceByDate(scope.row, date) || '-' }}
          </span>
          </template>
        </el-table-column>

      </el-table>
    
    <pagination
      v-show="total"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />



    <!-- 考勤详情对话框 -->
    <!-- 考勤详情对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="考勤政策详情"
        width="70%"
        :before-close="handleClose"
    >
      <template #default>
        <div class="policy-detail-container">
          <!-- 左侧政策列表 -->
          <div class="policy-list">
            <el-menu
                :default-active="selectedPolicy.id.toString()"
            >
              <el-menu-item
                  v-for="policy in policiesList"
                  :key="policy.id"
                  :index="policy.id.toString()"
                  @click="changeSeclectPolicy(policy)"
              >
                <span class="policy-name-left">{{ policy.policyName }}</span>
                <!--<span class="policy-description">这个id为: {{ policy.id }}</span>-->
              </el-menu-item>
            </el-menu>

          </div>

          <!-- 右侧政策详情 -->
          <div class="policy-details" v-if="selectedPolicy">

            <div class="policy-header">
              <el-row :gutter="10">
                <el-col :span="5">
                  <div class="policy-info">
                    <span class="policy-name">政策名称: </span>
                  </div>
                </el-col>
                <el-col :span="19">
                  <div class="policy-info">
                    <span class="policy-value">{{ selectedPolicy.policyName }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="5">
                  <div class="policy-info">
                    <span class="policy-name">上班时间: </span>
                  </div>
                </el-col>
                <el-col :span="19">
                  <div class="policy-info">
                    <span class="policy-value">
                      <WorkTimeDisplay
                        :jsonStr="selectedPolicy.workTimeJson"
                        :showJson="false"
                      />
                    </span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="5">
                  <div class="policy-info">
                    <span class="policy-name">打卡成功的容忍时间范围, 即在规定上班时间后N分钟内可以成功打卡,  在下班时间的前N分钟内不会被认为早退: </span>
                  </div>
                </el-col>
                <el-col :span="19">
                  <div class="policy-info">
                    <span class="policy-value">{{ selectedPolicy.tolerateTimes }}分钟</span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="5">
                  <div class="policy-info">
                    <span class="policy-name">加班起始时间（下班时间后N分钟开始算加班）: </span>
                  </div>
                </el-col>
                <el-col :span="19">
                  <div class="policy-info">
                    <span class="policy-value">{{ selectedPolicy.overtimeStart }}分钟</span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="5">
                  <div class="policy-info">
                    <span class="policy-name">每日标准工作时长（小时）: </span>
                  </div>
                </el-col>
                <el-col :span="19">
                  <div class="policy-info">
                    <span class="policy-value">{{ selectedPolicy.workHoursPerDay }}小时</span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="5">
                  <div class="policy-info">
                    <span class="policy-name">政策描述: </span>
                  </div>
                </el-col>
                <el-col :span="19">
                  <div class="policy-info">
                    <span class="policy-value">{{ selectedPolicy.description }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>

          </div>

          <!-- 无选择时的提示 -->
          <div class="policy-details" v-else>
            <el-empty description="请选择一个考勤政策"></el-empty>
          </div>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAttendance" :disabled="disableOkButton">确认</el-button>
        </span>
      </template>
    </el-dialog>



  </div>
</template>

<script setup name="Attendance">
import { listAttendance, getAttendance, delAttendance, addAttendance, updateAttendance } from "@/api/attendance/attendance"
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage} from 'element-plus';
import {addPolicies, delPolicies, getPolicies, listPolicies, updatePolicies} from "@/api/attendance/policies"
import WorkTimeDisplay from '@/views/attendance/components/WorkTimeDisplay.vue';


// const tabPosition = ref<TabsInstance['tabPosition']>('left')
const tabPosition = ref('top')

const { proxy } = getCurrentInstance()

const dateRangeDays = ref([]);
// 对话框状态
const dialogVisible = ref(false)
const dialogData = ref({
  userId: null,
  scheduleDate: null,
  policyId: null,
  policyName: null
})
// 考勤政策列表
const policiesList = ref([])
const selectedPolicy = ref(null) // 当前选中的政策
const selectedUserId = ref(null) // 当前选中的用户ID
const selectedScheduleDate = ref(null) // 当前选中的日期
const disableOkButton = ref(false) // 确认按钮是否禁用



const attendanceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeScheduleDate = ref([])
const daterangeCreatedAt = ref([])

// 定义自己的daterange
const daterange1 = ref([]);

// ry初始数据
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // userId: null,
    // userPosition: null,
    // scheduleDate: null,
    // attendancePoliciesId: null,
    // createdAt: null
    // private String keyword;           // 搜索关键词
    // private Date startDate;           // 开始日期
    // private Date endDate;

    keyword: null,
    startDate: null,
    endDate: null,


  },
  rules: {
    userId: [
      { required: true, message: "用户ID，关联员工表不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询员工排班管理列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  // if (null != daterangeScheduleDate && '' != daterangeScheduleDate) {
  //   queryParams.value.params["beginScheduleDate"] = daterangeScheduleDate.value[0]
  //   queryParams.value.params["endScheduleDate"] = daterangeScheduleDate.value[1]
  // }
  if (null != daterangeCreatedAt && '' != daterangeCreatedAt) {
    queryParams.value.params["beginCreatedAt"] = daterangeCreatedAt.value[0]
    queryParams.value.params["endCreatedAt"] = daterangeCreatedAt.value[1]
  }

  if (null!= daterange1 && ''!= daterange1) {
    queryParams.value.params["startDate"] = daterange1.value[0]
    queryParams.value.params["endDate"] = daterange1.value[1]

    queryParams.value.startDate = daterange1.value[0]
    queryParams.value.endDate = daterange1.value[1]

    console.log("startDate:"+daterange1.value[0])
    console.log("endDate:"+daterange1.value[1])
  }



  console.log("list接口请求参数：" + JSON.stringify(queryParams.value))
  listAttendance(queryParams.value).then(response => {
    // console.log("list接口返回数据：" + JSON.stringify(response))

    attendanceList.value = response.rows
    // console.log("attendanceList:"+JSON.stringify(attendanceList.value))
    total.value = response.total
    loading.value = false
  })

  calculateDateRange()
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    userPosition: null,
    scheduleDate: null,
    attendancePoliciesId: null,
    delFlag: null,
    createdAt: null,
    keyword: null,
  }
  proxy.resetForm("attendanceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeScheduleDate.value = []
  daterangeCreatedAt.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  console.log("点进了新增按钮")
  addAttendance(form.value).then(response => {
    proxy.$modal.msgSuccess("新增成功")
    open.value = false
    getList()
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getAttendance(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改员工排班管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["attendanceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAttendance(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAttendance(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除员工排班管理编号为"' + _ids + '"的数据项？').then(function() {
    return delAttendance(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('attendance/attendance/export', {
    ...queryParams.value
  }, `attendance_${new Date().getTime()}.xlsx`)
}

getList()


// 计算日期范围
function calculateDateRange(){
  console.log("计算日期范围："+daterange1.value)

  // 初始化或者格式化
  if (!daterange1.value || daterange1.value.length < 2) {
    // 代表没有选择日期范围，或者选择了不完整的日期范围
    // 这里可以根据需要设置默认值，比如设置为今天到30天后的日期范围
    daterange1.value = getDefaultDateRange();
  }
  // 计算日期范围
  const days = [];
  const startDate = new Date(daterange1.value[0]);
  const endDate = new Date(daterange1.value[1]);

  // 确保开始日期小于结束日期
  if (startDate > endDate)
  {
    console.log("开始日期大于结束日期")
  }

  // 生成日期范围内的所有日期
  const currentDate = new Date(startDate);
  while (currentDate <= endDate) {
    days.push(currentDate.toISOString().split('T')[0]); // YYYY-MM-DD
    currentDate.setDate(currentDate.getDate() + 1);
  }
  console.log("最终的dateRangeDays:"+days)

  dateRangeDays.value = days;

}


// 获取默认日期范围（今天和30天后）
function getDefaultDateRange() {
  const today = new Date();
  const endDate = new Date(today);
  endDate.setDate(today.getDate() + 30);

  return [
    formatDate(today),
    formatDate(endDate)
  ];
}

// 日期格式化函数
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}


// 格式化日期标签（显示周几）
const formatDateLabel = (dateString) => {
  const date = new Date(dateString);
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  return `${date.getMonth() + 1}/${date.getDate()} ${weekdays[date.getDay()]}`;
};

// 获取考勤政策
const getAttendanceByDate = (row, date) => {
  if (!row.scheduleList || row.scheduleList.length === 0) return '';

  const scheduleItem = row.scheduleList.find(item => item.scheduleDate === date);
  // console.log("本列的scheduleItem:"+JSON.stringify(scheduleItem))
  return scheduleItem?.policyName || '';
};

// 处理日期选择范围
function formatDateRange(num){

  console.log("daterange1:"+daterange1.value)
  console.log(daterange1.value.length)
  console.log(daterange1.value[0])
  console.log(daterange1.value[1])

  // 获取当前日期和30天后的日期
  const today = new Date();
  const maxEndDate = new Date(today);
  maxEndDate.setDate(today.getDate() + 30);

  // 解析日期
  const [startDateStr, endDateStr] = daterange1.value;
  const startDate = new Date(startDateStr);
  let endDate = new Date(endDateStr);

  // 调整结束日期
  if (endDate > maxEndDate) {
    endDate = maxEndDate;
    daterange1.value[1] = endDate.toISOString().split('T')[0];
  }

  // 调整开始日期
  if (startDate >= endDate) {
    const newStartDate = new Date(endDate);
    newStartDate.setDate(endDate.getDate() - 7);
    daterange1.value[0] = newStartDate.toISOString().split('T')[0];
  }

  console.log("调整后的daterange1:"+daterange1.value)


}

// 事件处理
const handleCellClick = (row, date, event) => {
  console.log('点击的行数据:', row)
  console.log('点击的日期:', date)
  console.log('原生事件对象:', event)

  // 检查日期是否为当天之前
  const currentDate = new Date().toISOString().split('T')[0]; // 获取当前日期，格式为 'YYYY-MM-DD'
  const clickedDate = new Date(date).toISOString().split('T')[0];

  // 添加日期标记
  disableOkButton.value = clickedDate <= currentDate;
  console.log('日期标记:', disableOkButton.value); // 输出标记结果

  selectedScheduleDate.value = date;

  const scheduleItem = row.scheduleList.find(item => item.scheduleDate === date);
  const userId = row.userId;

  // // 从考勤政策policiesList中获取id一样数据
  // const policy = policiesList.value.find(item => item.id === scheduleItem.policyId);
  // selectedPolicy.value = policy;

  // 这里可以添加更多处理逻辑
  showAttendanceDetail(userId, scheduleItem)
}

const showAttendanceDetail = (userId, scheduleItem) => {

  // 从考勤政策policiesList中获取id一样数据
  const policy = policiesList.value.find(item => item.id === scheduleItem.policyId);
  selectedPolicy.value = policy;
  selectedUserId.value = userId;


  console.log("获取的用户ID："+userId)
  console.log("筛选出来的这个单元格的考勤政策数据："+JSON.stringify(scheduleItem))
  // 后续可以扩展为打开详情对话框等操作

  console.log("设置对话框数据,此时的dialogVisible:"+dialogVisible.value)
  if (scheduleItem) {
    dialogData.value = {
      userId,
      scheduleDate: scheduleItem.scheduleDate,
      policyId: scheduleItem.policyId,
      policyName: scheduleItem.policyName
    }
    dialogVisible.value = true
  } else {
    // 处理没有考勤记录的情况
    dialogData.value = {
      userId,
      scheduleDate: '无记录',
      policyId: '无记录',
      policyName: '无记录'
    }

    dialogVisible.value = true
  }
  console.log("设置对话框数据后，此时的dialogVisible:"+dialogVisible.value)

}

const changeSeclectPolicy = (policy) => {
  console.log("changeSeclectPolicy:"+JSON.stringify(policy))
  selectedPolicy.value = policy;
}


const handleClose = (done) => {
  dialogVisible.value = false
  done()
}

const confirmAttendance = () => {
  if (!selectedPolicy.value) {
    ElMessage.warning('请选择一个考勤政策')
    return
  }

  console.log('确认考勤政策:', selectedPolicy.value)
  console.log('用户ID:', selectedUserId.value)

  let  params = {
    userId: selectedUserId.value,
    attendancePoliciesId: selectedPolicy.value.id,
    scheduleDate:selectedScheduleDate.value
  }

  updateAttendance(params).then(response => {
    proxy.$modal.msgSuccess("修改成功")
    dialogVisible.value = false
    console.log("修改接口获取的数据")
    console.log(response)
    getList()
  })


  // 这里可以添加确认后的处理逻辑

}

/** 查询考勤政策/排班详情列表 */
function getList1() {
  loading.value = true

  // 设置一个专属的查询参数, 分页为1页, 大小为1000
  const queryParams1 = {
    pageNum: 1,
    pageSize: 1000,
    // 可以根据需要添加其他查询条件
  }


  listPolicies(queryParams1).then(response => {

    console.log("listPolicies接口返回数据：", response)
    policiesList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log("policiesList:", policiesList.value)
  })

}

getList1()

</script>


<style scoped>
.container {
  padding: 20px;
}

.cell-content {
  display: inline-block;
  padding: 5px;
  border-radius: 4px;
}

.cell-content:hover {
  background-color: #f5f7fa;
}

.policy-detail-container {
  display: flex;
  gap: 15px;
}

.policy-list {
  flex: 1;
  max-width: 150px;
}

.policy-details {
  flex: 2;
}

.detail-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.label {
  width: 120px;
  color: #606266;
}

.value {
  flex: 1;
  color: #303133;
}

.policy-name {
  font-weight: 500;
}

.selected {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}
/* 政策详情区域样式 */
.policy-details {
  padding: 15px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  height: 100%;
}

.policy-header {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.policy-info {
  padding: 8px 0;
  border-radius: 4px;
}

.policy-name {
  font-weight: 500;
  color: #606266;
  display: inline-block;
  width: 100%;
  text-align: right;
  padding-right: 10px;
}

.policy-value {
  color: #303133;
  display: inline-block;
  width: 100%;
}

/* 长描述样式优化 */
.policy-info:last-child .policy-value {
  line-height: 1.6;
  background-color: #f9fafc;
  padding: 10px 12px;
  border-radius: 4px;
}

/* 行悬停效果 */
.el-row:hover .policy-info {
  background-color: #f5f7fa;
  transition: background-color 0.2s ease;
}

</style>
